package com.youlu.campus.service.item;

import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;

import com.youlu.campus.entity.ActivityCultureCreativeConfig;
import com.youlu.campus.entity.ItemInfo;
import com.youlu.campus.entity.VO.req.ActivityCultureCreativeReq;
import com.youlu.campus.entity.VO.req.ItemQueryReq;
import com.youlu.campus.entity.VO.res.ActivityCultureCreativeResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.repository.support.PageableExecutionUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ActivityCultureCreativeConfigService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private ItemInfoService itemInfoService;

    public Page<ActivityCultureCreativeResponse> index(ActivityCultureCreativeReq cultureCreativeReq) {
        PageRequest pageRequest = PageRequest.of(cultureCreativeReq.getPage() - 1, cultureCreativeReq.getPageSize());
        Query query = new Query();
        query.addCriteria(Criteria.where("activityId").is(cultureCreativeReq.getActivityId()));
        query.addCriteria(Criteria.where("deleted").is(Boolean.FALSE));
        query.with(Sort.by(Sort.Direction.DESC, "like", "createdTime"));
        List<ActivityCultureCreativeConfig> list = this.mongoTemplate.find(query.with(pageRequest), ActivityCultureCreativeConfig.class);
        if (CollectionUtils.isEmpty(list)) {
            return PageableExecutionUtils.getPage(new ArrayList<>(), pageRequest, () -> 0L);
        }
        long count = this.mongoTemplate.count(query, ActivityCultureCreativeConfig.class);
        List<String> itemIdList = list.stream().map(ActivityCultureCreativeConfig::getItemInfoId).collect(Collectors.toList());
        query = new Query();
        query.addCriteria(Criteria.where("id").in(itemIdList));
        List<ItemInfo> itemInfoList = this.mongoTemplate.find(query, ItemInfo.class);
        List<ActivityCultureCreativeResponse> result = itemInfoList.stream().map(itemInfo -> {
            ActivityCultureCreativeResponse cultureCreativeResponse = new ActivityCultureCreativeResponse();
            cultureCreativeResponse.setId(itemInfo.getId());
            if (CollectionUtils.isNotEmpty(itemInfo.getImageUrls())) {
                cultureCreativeResponse.setItemImageUrl(itemInfo.getImageUrls().get(0));
            }
            //cultureCreativeResponse.setDetail(itemInfo.getDetail());
            cultureCreativeResponse.setPrice(itemInfo.getPrice());
            cultureCreativeResponse.setTitle(itemInfo.getTitle());
            cultureCreativeResponse.setLike(itemInfo.getLike());
            return cultureCreativeResponse;
        }).collect(Collectors.toList());
        return PageableExecutionUtils.getPage(result, pageRequest, () -> count);
    }


    public void saveOrUpdate(ActivityCultureCreativeConfig activityCultureCreativeConfig) {
        Date now = new Date();
        if (StringUtils.isBlank(activityCultureCreativeConfig.getActivityId()) || StringUtils.isBlank(activityCultureCreativeConfig.getItemInfoId())) {
            log.error(":>>> 活动ID或商品ID为空");
            return;
        }

        ItemInfo info = itemInfoService.detail(activityCultureCreativeConfig.getItemInfoId());
        if (Objects.nonNull(info)) {
            activityCultureCreativeConfig.setLike(info.getLike());
            activityCultureCreativeConfig.setTitle(info.getTitle());
        }
        if (StringUtils.isBlank(activityCultureCreativeConfig.getId())) {
            activityCultureCreativeConfig.setCreatedTime(now);
            Query query = new Query();
            query.addCriteria(Criteria.where("itemInfoId").is(activityCultureCreativeConfig.getItemInfoId()).and("activityId").is(activityCultureCreativeConfig.getActivityId()));
            boolean exisit = mongoTemplate.exists(query, ActivityCultureCreativeConfig.class);
            if (exisit) {
                return;
            }
        } else {
            activityCultureCreativeConfig.setUpdatedTime(now);
        }
        this.mongoTemplate.save(activityCultureCreativeConfig);
    }

    public Page<ActivityCultureCreativeConfig> list(ItemQueryReq itemQueryReq) {
        PageRequest pageRequest = PageRequest.of(itemQueryReq.getPageNo() - 1, itemQueryReq.getPageSize());
        Query query = new Query();
        query.addCriteria(Criteria.where("activityId").is(itemQueryReq.getActivityId()));
        query.addCriteria(Criteria.where("deleted").ne(true));
        if (StringUtils.isNotBlank(itemQueryReq.getTitle())) {
            Pattern pattern = Pattern.compile("^.*" + itemQueryReq.getTitle() + ".*$", Pattern.CASE_INSENSITIVE);
            query.addCriteria(Criteria.where("title").regex(pattern));
        }
        long count = this.mongoTemplate.count(query, ActivityCultureCreativeConfig.class);
        if (count == 0) {
            return PageableExecutionUtils.getPage(new ArrayList<>(), pageRequest, () -> count);
        }
        query.with(Sort.by(Sort.Direction.DESC, "createdTime"));
        List<ActivityCultureCreativeConfig> list = this.mongoTemplate.find(query.with(pageRequest), ActivityCultureCreativeConfig.class);
        list.stream().forEach(activityCultureCreativeConfig -> {
            ItemInfo itemInfo = itemInfoService.detail(activityCultureCreativeConfig.getItemInfoId());
            if (Objects.nonNull(itemInfo)) {
                activityCultureCreativeConfig.setPrice(itemInfo.getPrice());
                activityCultureCreativeConfig.setTitle(itemInfo.getTitle());
                if (CollectionUtils.isNotEmpty(itemInfo.getImageUrls())) {
                    activityCultureCreativeConfig.setItemImageUrl(itemInfo.getImageUrls().get(0));
                }
            }
        });
        return PageableExecutionUtils.getPage(list, pageRequest, () -> count);
    }

    public boolean delete(String id) {
        Query query = new Query();
        query.addCriteria(Criteria.where("id").is(id));
        DeleteResult updateResult = mongoTemplate.remove(query, ActivityCultureCreativeConfig.class);
        return updateResult.getDeletedCount() > 0 ? true : false;
    }

    /**
     * 获取商品列表
     *
     * @param cultureCreativeReq
     * @return
     */
    public Page<ItemInfo> getItemList(ActivityCultureCreativeReq cultureCreativeReq) {
        PageRequest pageRequest = PageRequest.of(cultureCreativeReq.getPage() - 1, cultureCreativeReq.getPageSize());
        Query query = new Query();
        query.addCriteria(Criteria.where("onSale").ne(false));
        query.addCriteria(Criteria.where("category").is("cultureCreative"));
        query.with(Sort.by(Sort.Direction.DESC, "like", "createdTime"));
        List<ItemInfo> list = this.mongoTemplate.find(query.with(pageRequest), ItemInfo.class);
        if (CollectionUtils.isEmpty(list)) {
            return PageableExecutionUtils.getPage(new ArrayList<>(), pageRequest, () -> 0L);
        }
        long count = this.mongoTemplate.count(query, ItemInfo.class);
        return PageableExecutionUtils.getPage(list, pageRequest, () -> count);
    }

    @Async
    public void doOnSaleByItemId(String itemId,Boolean onSale){
        Query query = new Query();
        query.addCriteria(Criteria.where("itemInfoId").is(itemId));
        Update update = new Update();
        if(onSale){
            update.set("deleted",Boolean.FALSE);
        }else{
            update.set("deleted",Boolean.TRUE);
        }
        this.mongoTemplate.updateMulti(query,update,ActivityCultureCreativeConfig.class);
    }

}
